import { defineStore } from 'pinia';
import { getInfo, logout } from '@/api/login';

export const useUserStore = defineStore('user', {
  state: () => ({
    // token: uni.getStorageSync('token') || '',
    token: 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxNTM1NDE5NjQ1MyIsImxvZ2luX3RlbmFudF9pZCI6MSwibG9naW5fdXNlcl9rZXkiOiI5YjE2NWM1OC0zOTIwLTQ3MzEtOWEwZi1kMzAwMmI0NTVlN2MifQ.v5XQF798iI52n_2Lbkz-hdbMzzi61F6g_OZaZzVX5_cCPOduC57vfCUqNz1Pwxvu8wG-5FxMl7reedpS68Ji2w',
    userInfo: {
      userId: '',
      userName: '',
      nickName: '',
      avatar: '',
      roles: [],
      permissions: []
    }
  }),
  actions: {
    // 设置token
    setToken(token) {
      uni.setStorageSync('token', token);
      this.token = token;
    },
    getUserInfo() {
      return getInfo()
        .then(res => {
          const user = res.user;

          let avatar = '';
          if (user.avatar) {
            avatar = user.avatar?.startsWith('/') ? `${user.avatar}` : `/${user.avatar}`;
          }
          const userInfo = {
            ...user,
            userRoles: user.roles,
            avatar: avatar,
            roles: res.roles?.length > 0 ? res.roles : ['ROLE_DEFAULT'],
            permissions: res.roles?.length > 0 ? res.permissions : []
          };
          this.userInfo = { ...this.userInfo, ...userInfo };

          return Promise.resolve(userInfo);
        })
        .catch(Promise.reject);
    },
    clearLoginInfo() {
      this.token = '';
      this.userInfo = {};
      uni.setStorageSync('token', '');
    },
    // 退出系统
    logOut() {
      return logout().finally(() => {
        this.clearLoginInfo();
      });
    },
    loginInvalid() {
      this.clearLoginInfo();
      uni.reLaunch({
        url: `/pages/enterFromLingxinren/index`
      });
    }
  }
});
